#include "rrtracer.h"
#include "rrprim.h"

RRTracer::RRTracer()
{
}

void RRTracer::rrSetPrimSet(RRPrimSet *arg)
{
    primset = arg;
}

void RRTracer::rrSetPrim(RRPrim *arg)
{
    primset->rrSetPrim(arg);
}

void RRTracer::rrGenerateEye(float xs, float ys)
{
    eye.rrGenerateEye(RRSetVec3(xs, ys, eye.rrGetScreenPos()));
}

int RRTracer::rrCheckHit()
{
    RRRay r;
    r.rrSetSrc(eye.rrGetEyeCoord());
    r.rrSetDir(eye.rrGetEyeDir());

    float d, dmin;
    int it, index;
    dmin = 1.0e+14;
    it = primset->rrBegin();
    index = -1;
    while(it != primset->rrEnd()) {
        RRPrim *p;
        p = primset->rrGetPrim(it);
        d = p->rrHit(r);
        //printf("distance:%f\n", d);
        if(d < dmin && d > 0.0f) {
            dmin = d;
            index = it;
        }
        it++;
    }
    return index;
}

RRVec4 RRTracer::rrTrace()
{
    int hit = -1;
    hit =  rrCheckHit();
    //printf("%d\n", hit);
    RRVec4 c = RRSetVec4(0.0f, 0.0f, 0.0f, 0.0f);
    if(hit != -1) {
        RRPrim *p;
        p = primset->rrGetPrim(hit);
        c = p->rrTrace();
    }
    return c;
}

RRLight RRTracer::rrGetLight()
{
    return light;
}
